<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>构造函数中使用访问器</title>
  </head>
  <body></body>
  <script>
    let DATA = Symbol();
    function User(name, age) {
      let data = { name, age };
      Object.defineProperties(this, {
        name: {
          get() {
            return data.name;
          },
          set(value) {
            if (value.trim() == "" || value > 20) {
              throw new Error("用户名不合法！");
            }
            data.name = value;
          }
        },
        age: {
          get() {
            return data.age;
          },
          set(value) {
            if (typeof value != "number") {
              throw new Error("年龄不合法！");
            }
            data.age = value;
          }
        }
      });
    }
    let xj = new User("向军", 19);
    xj.name = "后盾人";
    xj.age = 13;

    console.log(xj);
  </script>
</html>
